package com.rd.sys.action.analysis;

import com.rd.sys.action.BaseAction;
import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.fileexport.ExportFile;
import com.rd.sys.common.utils.JacksonMapper;
import com.rd.sys.common.utils.cache.AnalysisCache;
import com.rd.sys.common.utils.client.AnalysisPathUtils;
import com.rd.sys.common.utils.crypto.BASE64;
import com.rd.sys.dto.analysis.statistic.StatisticExportDto;
import com.rd.sys.dto.client.store.Result;
import com.rd.sys.dto.commmon.enums.ExportEnum;
import com.rd.sys.dto.sys.user.UserInfoDto;
import com.rd.sys.service.analysis.result.ResultService;
import com.rd.sys.service.analysis.scheme.SchemeService;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class ImageAction extends BaseAction {
    private static final long serialVersionUID = 678540922983982387L;

    // -------------------------------------以下是数据成员定义-------------------------------------------

    @Autowired
    private SchemeService schemeService;

    private String projectCode;
    private String schemeCode;
    private String materialCode;
    private String materialSuffix;

    // ------------------------------------------以下是业务方法------------------------------------------
    public void show() {
        UserInfoDto userinfo = this.getUser(request);

        schemeService.showMaterialImage(userinfo.getUsercode(), projectCode, schemeCode, materialCode, materialSuffix,
                response);
    }

    /**
     *
     */
    public void save() throws Exception{
        Map<String,String> reMap = new HashMap<String, String>();
        try {
            Map<String,String[]> map = request.getParameterMap();
            if (map == null || map.isEmpty()){
                System.out.println("没有请求参数");
                return;
            }
            String userCode = parMapVal(map, "data[userCode]");
            String projectCode = parMapVal(map, "data[projectCode]");
            String schemeCode = parMapVal(map, "data[schemeCode]");
            String materialCode = parMapVal(map ,"data[materialCode]");
            String materialType = parMapVal(map, "data[materialType]");
            String key = userCode + CommonConstants.AnalysisConstats.CACHE_SPLIT + projectCode
                    + CommonConstants.AnalysisConstats.CACHE_SPLIT + schemeCode;
            String resultCode = readResultCode(key, parMapVal(map,"data[checkBoxName]"));
            // 生成文件路径
            String path = AnalysisPathUtils.findSchemePath(userCode,projectCode,schemeCode)
                    +resultCode+CommonConstants.SysParamConstants.FILE_SEPARATOR+"data"+CommonConstants.SysParamConstants.FILE_SEPARATOR;
            File outFile = new File(path);
            if (!outFile.exists()){
                if (!outFile.mkdirs()){
                    throw new RuntimeException("不能创建文件目录");
                }
            }
            System.out.println(path);
            String heatMap = parMapVal(map,"data[images][0][base]");
            if (StringUtils.isNotBlank(heatMap)){
                saveImage(URLDecoder.decode(heatMap, "utf-8"),path+"heatMap.jpg");
            }
            String routeMap = parMapVal(map, "data[images][1][base]");
            if (StringUtils.isNotBlank(routeMap)){
                saveImage(URLDecoder.decode(routeMap, "utf-8"),path+"routeMap.jpg");
            }
            String focusMap = parMapVal(map, "data[images][2][base]");
            if (StringUtils.isNotBlank(focusMap)){
                saveImage(URLDecoder.decode(focusMap, "utf-8"),path+"focusMap.jpg");
            }
            String gridMap = parMapVal(map, "data[images][3][base]");
            if (StringUtils.isNotBlank(gridMap)){
                saveImage(URLDecoder.decode(gridMap, "utf-8"),path+"gridMap.jpg");
            }
            String interestArea = parMapVal(map, "data[images][4][base]");
            if (StringUtils.isNotBlank(interestArea)){
                saveImage(URLDecoder.decode(interestArea, "utf-8"),path+"interestArea.jpg");
            }

            // 保存报表
            StatisticExportDto exportDto = new StatisticExportDto(this.getUser(request).getUsercode(), projectCode,
                    schemeCode, resultCode, materialCode);
            // 保存注视点
            ExportEnum.Type type = ExportEnum.Type.StatFixationData;
            File f1 = new File(path+"StatFixation.csv");
            ExportFile.preProcess(type.getCode(),f1);
            ExportFile.process(type.getCode(),f1,exportDto);

            // 保存扫视点
            type = ExportEnum.Type.StatSaccadeData;
            File f2 = new File(path+"StatSaccade.csv");
            ExportFile.preProcess(type.getCode(),f2);
            ExportFile.process(type.getCode(),f2,exportDto);

            // 保存
            type = ExportEnum.Type.StatPupilData;
            File f3 = new File(path+"StatPupil.csv");
            ExportFile.preProcess(type.getCode(),f3);
            ExportFile.process(type.getCode(),f3,exportDto);


            response.setContentType("application/json");
            response.setStatus(200);
            reMap.put("result","success");
            response.getWriter().write(JacksonMapper.bean2Json(reMap));
        }catch (Exception e){
            e.printStackTrace();
            reMap.put("result","failed");
            response.setContentType("application/json");
            response.setStatus(500);
            response.getWriter().write(JacksonMapper.bean2Json(reMap));
        }

    }


    private String readResultCode(String key, String val){
        try {
            List<Result> listResult = AnalysisCache.ResultCache.get(key);
            for (Result result : listResult){
                if (result.getResultName().equals(val)){
                    return result.getResultCode();
                }
            }
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return "";
    }

    private String parMapVal(Map<String,String[]> map, String key){
        String[] strArr = map.get(key);
        if (strArr != null && strArr.length >0){
            return strArr[0];
        }
        return null;
    }

    private boolean saveImage(String imageStr, String fileName){
        if (StringUtils.isBlank(imageStr)){
            return false;
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            imageStr = imageStr.substring(imageStr.indexOf(",")+1);
            byte[] b = BASE64.decode(imageStr);
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            fos.write(b);
            fos.flush();
            fos.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    // ------------------------------------------以下是get/set方法-----------------------------------------

    public String getProjectCode() {
        return projectCode;
    }

    public void setProjectCode(String projectCode) {
        this.projectCode = projectCode;
    }

    public String getSchemeCode() {
        return schemeCode;
    }

    public void setSchemeCode(String schemeCode) {
        this.schemeCode = schemeCode;
    }

    public String getMaterialCode() {
        return materialCode;
    }

    public void setMaterialCode(String materialCode) {
        this.materialCode = materialCode;
    }

    public String getMaterialSuffix() {
        return materialSuffix;
    }

    public void setMaterialSuffix(String materialSuffix) {
        this.materialSuffix = materialSuffix;
    }

}
